#include <U8g2lib.h>

#define INT_PIN 2
#define READ_PIN 3
#define RESET_PIN 8

U8G2_SSD1306_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/A2, /* dc=*/A1, /* reset=*/A0);

volatile unsigned long time = 0;
volatile unsigned long last_time = 0;

//volatile int state = LOW;
//int code[95] = { 1,0,1,0,0,1,0,0,1,1,0,1,1,1,1,0,1,0,0,1,1,1,0,1,0,1,1,0,0,0,1,0,0,0,0,1,0,1,0,1,1,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,1,0,1,1,1,0,0,1,0,0,1,1,1,0,1,0,1,0,0,0,0,1,0,0,0,0,1,0,1,0,0,1,0,0,0,1,0,1 };
int code[95] = { 0 };
volatile int index = 0;
bool fresh_flag = true;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(READ_PIN, INPUT_PULLUP);
  pinMode(RESET_PIN, INPUT_PULLUP);
  u8g2.begin();
  //u8g2.setContrast(0);
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_ncenB08_tr);
  attachInterrupt(0, read_data, CHANGE);
}

void loop() {
  if (!digitalRead(RESET_PIN)) {
    attachInterrupt(0, read_data, CHANGE);
    index = 0;
    memset(code, 0, 95 * 2);
    fresh_flag = true;
  }
  if (fresh_flag) {
    //绘制条形码
    u8g2.clearBuffer();
    u8g2.setDrawColor(1);
    u8g2.drawBox(0, 0, 128, 64);

    for (int i = 0; i < 95; i++) {
      if (code[i] == 1) {
        u8g2.setDrawColor(0);  //黑
        if (i == 0 || i == 2 || i == 46 || i == 48 || i == 92 || i == 94) {
          u8g2.drawLine(i + 10, 0, i + 10, 50);
        } else {
          u8g2.drawLine(i + 10, 0, i + 10, 45);
        }
      }
    }
    char str[3];
    sprintf(str, "%2d", index);
    u8g2.setDrawColor(0);  //黑
    u8g2.drawStr(2, 58, str);
    u8g2.sendBuffer();
    fresh_flag = false;
  }
}

void read_data() {
  time = millis();
  if (time - last_time > 10) {
    int data = digitalRead(READ_PIN);
    digitalWrite(LED_BUILTIN, data);
    code[index] = data;
    index++;
    if (index == 96) {
      index == 0;
      detachInterrupt(0);
    }
    fresh_flag = true;
    last_time=millis();
  }
}